package com.itheima;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.zip.GZIPInputStream;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class QWeatherClient {
    private static final String API_HOST = "https://mb7p42dfjr.re.qweatherapi.com"; // 你的 API Host
    private static final String API_KEY = "bb7a50fa6bf145ab93ef1cc4fc06820e"; // 你的 API Key

    private HttpClient client;
    private ObjectMapper objectMapper;

    public QWeatherClient() {
        this.client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();
        this.objectMapper = new ObjectMapper();
    }

    // 获取实时天气
    public WeatherNow getNow(String locationId) throws IOException, InterruptedException {
        String url = String.format("%s/v7/weather/now?location=%s", API_HOST, locationId);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Accept-Encoding", "gzip")
                .header("X-QW-Api-Key", API_KEY)
                .GET()
                .build();

        HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());

        if (response.statusCode() != 200) {
            throw new IOException("请求失败：" + response.statusCode() + " - " + new String(response.body()));
        }

        // 解压 Gzip 数据
        String json = decompressGzip(response.body());

        // 解析 JSON 数据
        JsonNode root = objectMapper.readTree(json);

        // 获取当前天气
        JsonNode now = root.path("now");

        return new WeatherNow(
                root.path("updateTime").asText(),
                now.path("temp").asText(),
                now.path("text").asText(),
                now.path("windDir").asText(),
                now.path("windSpeed").asText(),
                now.path("humidity").asText()
        );
    }

    // Gzip 解压函数
    private String decompressGzip(byte[] compressed) throws IOException {
        try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed))) {
            return new String(gis.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
        }
    }
}

